<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input clearable @clear="load" style="width: 260px; margin-right: 5px" v-model="data.title" placeholder="请输入标题查询" :prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查 询</el-button>
      <el-button @click="reset">重 置</el-button>
    </div>

    <div v-if="data.user.role === 'ADMIN'" class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-skeleton
          v-if="loading"
          :rows="6"
          animated    style="padding: 15px"
      />
      <el-table
        v-else
        v-loading="loading"
        element-loading-text="拼命加载中..."
        :data="data.tableData"
        style="width: 100%;"
        max-height="600px"
        stripe
        border
        highlight-current-row
        :row-style="{ height: '60px' }"
        :header-cell-style="{
          backgroundColor: '#f5f7fa',
          color: '#606266',
          fontWeight: 'bold'
        }"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div class="expand-content">
              <div class="content-box">
                {{ props.row.content }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="公告标题" />
        <el-table-column prop="author" label="作者" />
        <el-table-column prop="time" label="发布时间">
          <template #default="{row}">
            {{ formatTime(row.time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" v-if="data.user.role === 'ADMIN'">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button type="primary" icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 15]"
          :total="data.total"
          @current-change="load"
          @size-change="load"
      />
    </div>

    <el-dialog title="公告信息" v-model="data.formVisible" width="30%" destroy-on-close>
      <el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="80px" style="padding: 20px 30px 10px 0">
        <el-form-item prop="title" label="公告标题">
          <el-input v-model="data.form.title" autocomplete="off" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item prop="content" label="公告内容">
          <el-input type="textarea" :rows="3" v-model="data.form.content" autocomplete="off" placeholder="请输入公告内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">发 布</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {Search} from "@element-plus/icons-vue";
import {reactive, ref} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import moment from 'moment'

const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || "{}"),
  title: null,
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  form: {},
  formVisible: false,
  rules: {
    title: [
      { required: true, message: '请填写公告标题', trigger: 'blur' }
    ],
    content: [
      { required: true, message: '请填写公告内容', trigger: 'blur' }
    ],
  }
})

const formatTime = (time) => {
  return moment(time).format('YYYY-MM-DD HH:mm')
}

const formRef = ref()

const loading = ref()

const load = async () => {
  loading.value = true
  const startTime = Date.now() // 记录开始时间
  // 构造查询参数
  const params = {
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    title: data.title
  }
  try {
    const res = await request.get('/notice/selectPage', { params })

    if (res.code === '200') {
      data.tableData = res.data.list
      data.total = res.data.total
    } else {
      ElMessage.error(res.msg)
    }
  } catch (e) {
    ElMessage.error('数据加载失败')
  } finally {
    // 计算剩余需要等待的时间
    const elapsed = Date.now() - startTime
    const remaining = Math.max(500 - elapsed, 0)
    setTimeout(() => {
      loading.value = false
    }, remaining)
  }

}
load()

const handleAdd = () => {
  data.form = {}
  data.formVisible = true
}

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

const add = () => {
  data.form.author = data.user.name
  request.post('/notice/add', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('新增成功')
      data.formVisible = false
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const update = () => {
  request.put('/notice/update', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('更新成功')
      data.formVisible = false
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const save = () => {
  formRef.value.validate(valid => {
    if (valid) {
      data.form.id ? update() : add()
    }
  })
}

const del = (id) => {
  ElMessageBox.confirm('删除后无法恢复，您确认删除吗？', '删除确认', { type: 'warning' }).then(res => {
    request.delete('/notice/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {})
}

const reset = () => {
  data.title = null
  load()
}
</script>

<style scoped>
/* 展开行样式 */
.expand-content {
  padding: 20px;
  background: #f8f9fa;
  .content-box {
    max-width: 800px;
    margin: 0 auto;
    line-height: 1.6;
    color: #606266;
  }
}

/* 表格整体样式 */
.el-table {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
}

/* 行悬停效果 */
.el-table__body tr:hover>td {
  background-color: #f5f7fa !important;
  cursor: pointer;
}

/* 分页样式调整 */
.el-pagination {
  padding: 15px;
  justify-content: flex-end;
}
</style>